package com.gxa.saas.service.impl;

import com.gxa.saas.mapper.VisitCountMapper;
import com.gxa.saas.pojo.VisitCount;
import com.gxa.saas.pojo.VisitResult;
import com.gxa.saas.service.VisitCountService;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.List;


@Service
@Transactional(rollbackFor = Throwable.class)
public class VisitCountServiceImpl implements VisitCountService {

    @Autowired
    VisitCountMapper visitCountMapper;

    @Override
    public List<VisitCount> selectAll() {
        return visitCountMapper.selectAll();
    }

    @Override
    public List<VisitCount> selectByPage(Integer page, Integer size) {
        return visitCountMapper.selectByPage(page,size);
    }

    @Override
    public void export(List<VisitCount> list, HttpServletResponse response) throws Exception {
        HSSFWorkbook workbook = new HSSFWorkbook();

        HSSFSheet sheet = workbook.createSheet("拜访统计表");
        String fileName = "拜访统计列表.xls";

        fileName = URLEncoder.encode(fileName,"utf-8").replaceAll("\\+", "%20");

        String[] headers = { "序号", "客户类型", "门店名称","负责人","负责人电话","有效拜访次数","拜访次数"};

        HSSFRow row = sheet.createRow(0);
        for(int i=0;i<headers.length;i++){
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        int rowNum = 1;
        for (int i = 0; i < list.size(); i++) {
            HSSFRow dataRow = sheet.createRow(rowNum);
            dataRow.createCell(0).setCellValue(rowNum);
            dataRow.createCell(1).setCellValue(list.get(i).getCustomerType());
            dataRow.createCell(2).setCellValue(list.get(i).getName());
            dataRow.createCell(3).setCellValue(list.get(i).getLeaderPerson());
            dataRow.createCell(4).setCellValue(list.get(i).getPhone());
            dataRow.createCell(5).setCellValue(list.get(i).getEffectiveTime());
            dataRow.createCell(6).setCellValue(dateFormat.format(list.get(i).getVisitTime()));
            rowNum++;
        }

        //返回给前端下载
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());


    }

    @Override
    public VisitCount selectById(Integer id) {
     return    visitCountMapper.selectById(id);
    }

}
